package com.panopset.compat;

import java.io.PrintWriter;
import java.io.StringWriter;

public class TraceDump {

	private final StringWriter stw = new StringWriter();
	
	public TraceDump(Throwable t) {
		stw.append(getFullStackTrace(t));
	}

	@Override
	public String toString() {
		return stw.toString();
	}
	

    /**
     * @param t
     *            Throwable to get the stack trace from.
     * @return Stack trace.
     */
    private String getStackTrace(final Throwable t) {
        StringWriter sw = new StringWriter();
        try {
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.flush();
            pw.close();
            sw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return sw.toString();
    }

    /**
     * @param t
     *            Throwable to get the stack trace from.
     * @return Full stack trace, including causes.
     */
    private String getFullStackTrace(final Throwable t) {
    	String eol = Strings.getEol();
        StringWriter sw = new StringWriter();
        sw.append(t.getMessage());
        sw.append(eol);
        sw.append("*************************");
        sw.append(eol);
        sw.append(getStackTrace(t));
        sw.append(eol);
        Throwable cause = t.getCause();
        while (cause != null) {
            sw.append("*************************");
            sw.append(eol);
            sw.append(getStackTrace(cause));
            sw.append(eol);
            cause = cause.getCause();
        }
        return sw.toString();
    }

}
